'use strict'

const express = require('express')
const ejs = require('ejs')
const { default: axios } = require('axios');
const cookieParser = require('cookie-parser');

const PORT = 8080
const HOST = '0.0.0.0'

const app = express()
app.set('views', './views')
app.engine('html', ejs.__express)
app.set('view engine', 'html')
app.use(express.urlencoded({ extended: false }))
app.use(express.json())
app.use(express.static('views'))
app.use(cookieParser());

const static_reasouse = ['/login', '/register', '/welcome', '/order', '/dorm', '/result']
const services = {
    'giftapi': '139.224.246.43:8082',
    'orderapi': '139.224.246.43:8084',
    'usersapi': '139.224.246.43:8081',
}
const skip_jwt = ['/usersapi/getUserId']
const amd_url = ['addGift', 'giftListForAdmin', 'searchOrder3']

let static_rep = '(' + static_reasouse.join('|') + ')'

app.get(static_rep, function(request, response) {
    response.render(request.url.substr(1), {});
});

//使用中间件对api进行拦截，拦截后验证token
app.use('/*api', function(req, res, next) {
    let url = req.originalUrl
        //需要跳过的api进行过滤
    if (!skip_jwt.includes(url)) {
        let cookiestr = req.headers.cookie
        if (cookiestr == null) {

        }
        console.log(cookiestr)
            // let jwt_url = "http://139.224.246.43:8081/usersapi/getUserId"
            // let headers = req.headers
            // axios.post(jwt_url, headers).then(function(jwt_res) {
            //     console.log(jwt_res.data)
            //     if (jwt_res.data == null) {
            //         res.redirect('/login.html')
            //     }
            // }).catch(function(error) {
            //     console.log(error)
            // })
    }
    next()
})

//对所有路由进行转发
app.all('*', function(req, res) {
    if (req.url == '/usersapi/getUserId') {
        let url = "http://139.224.246.43:8081/usersapi/getUserId"
        let data = req.body
        let headers = req.headers
        let method = req.method
        console.log(url, data, headers, method)
        axios({
            method: method,
            url: url,
            data: data,
            headers: headers,
        }).then(function(response) {
            let amd = ['2101210156', '2101210674', '2101210524', '2101210251', '2101210475']
            var map = response.data
            console.log("---------------------------------------------")
            console.log(map)
            let keys = Object.keys(map)
            console.log(keys)
            if (keys.indexOf('userId') > -1) {
                console.log(amd.indexOf(map.userId))
                if (amd.indexOf(map.userId) == -1) {
                    for (let u in amd_url) {
                        console.log(headers.referer)
                        if (headers.referer.search(u) != -1) {
                            res.send({ 'code': 302 })
                            return
                        }
                    }
                }
                res.send(response.data)
            } else {
                res.redirect('/error.html')
            }

        }).catch(function(error) {
            console.log(error)
        })

    } else {
        for (let k in services) {
            if (req.url.search(k) != -1) {
                let url = "http://" + services[k] + req.url
                let data = req.body
                let headers = req.headers
                let method = req.method
                axios({
                    method: method,
                    url: url,
                    data: data,
                    headers: headers,
                }).then(function(response) {
                    res.send(response.data)
                }).catch(function(error) {
                    console.log('error2')
                })
            }
        }
    }

})

app.listen(PORT, HOST)